import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/store';
//创建axios实例
const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000
});
//请求拦截器
request.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    const token = userStore.user.token;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (e) => Promise.reject(e)
);
//响应拦截器
interface Data<T> {
  code: string | number;
  msg: string;
  data: T;
  rows: T;
}
request.interceptors.response.use(
  (response) => {
    if (response.data.code === 200) {
      return response.data;
    }
    ElMessage.error(response.data.msg);
    return Promise.reject(new Error(response.data.msg || '系统错误'));
  },
  (error) => {
    //异常处理
    if (error.response.data) {
      const { code, msg } = error.response.data;
      if (code === 401) {
        ElMessage.error('当前页面已失效，请重新登录');
      } else {
        ElMessage.error(msg || '请求失败');
      }
      return Promise.reject(error.msg || '请检查');
    }
  }
);
export default request;

/*自定义*/
// export const R={
//   /*判断是否为空*/
//   isEmpty:(str:any)=>{
//     return str === '' || str === null || str === undefined;
//   }
// }
